import { Dormitory } from '../models/Dormitory.js';
import { DormBuilding } from '../models/DormBuilding.js';
import { Student } from '../models/Student.js';

const dormitoryModel = new Dormitory();
const dormBuildingModel = new DormBuilding();
const studentModel = new Student();

export class DormitoryController {
  // 获取宿舍楼列表
  async getDormBuildings(req, res) {
    try {
      console.log('获取宿舍楼列表，查询参数:', req.query);
      
      const buildings = dormBuildingModel.findAll();
      
      // 处理分页
      const page = parseInt(req.query.page) || 1;
      const pageSize = parseInt(req.query.pageSize) || 10;
      const startIndex = (page - 1) * pageSize;
      const endIndex = startIndex + pageSize;
      
      // 应用搜索过滤
      let filteredBuildings = [...buildings];
      
      // 关键词搜索
      if (req.query.keyword) {
        const keyword = req.query.keyword.toLowerCase();
        filteredBuildings = filteredBuildings.filter(building => 
          building.name.toLowerCase().includes(keyword) ||
          (building.description && building.description.toLowerCase().includes(keyword))
        );
      }
      
      // 分页
      const paginatedBuildings = filteredBuildings.slice(startIndex, endIndex);
      
      // 构建响应
      const response = {
        data: paginatedBuildings,
        pagination: {
          current: page,
          pageSize: pageSize,
          total: filteredBuildings.length,
          totalPages: Math.ceil(filteredBuildings.length / pageSize)
        }
      };
      
      console.log('返回宿舍楼数据:', {
        dataCount: paginatedBuildings.length,
        total: filteredBuildings.length
      });
      
      res.json(response);
    } catch (error) {
      console.error('获取宿舍楼列表失败:', error);
      res.status(500).json({ error: '获取失败' });
    }
  }

  // 获取所有宿舍楼（用于下拉框）
  async getAllDormBuildings(req, res) {
    try {
      console.log('获取所有宿舍楼');
      const buildings = dormBuildingModel.findAll();
      res.json(buildings);
    } catch (error) {
      console.error('获取所有宿舍楼失败:', error);
      res.status(500).json({ error: '获取失败' });
    }
  }

  // 获取宿舍房间列表
  async getDormRooms(req, res) {
    try {
      console.log('获取宿舍房间列表，查询参数:', req.query);
      
      const dormitories = dormitoryModel.findAll();
      const students = studentModel.findAll();
      const buildings = dormBuildingModel.findAll(); // 添加获取宿舍楼数据
      
      // 处理分页参数
      const page = parseInt(req.query.current) || parseInt(req.query.page) || 1;
      const pageSize = parseInt(req.query.pageSize) || 10;
      const startIndex = (page - 1) * pageSize;
      const endIndex = startIndex + pageSize;
      
      // 转换数据格式
      const formattedDormitories = dormitories.map(dorm => {
        const members = students.filter(student => 
          student.dormBuilding === dorm.buildingName && 
          student.dormRoom === dorm.roomNumber
        );
        
        // 数据验证：检查是否超过容量
        if (members.length > dorm.totalBeds) {
          console.warn(`警告: 宿舍 ${dorm.buildingName} ${dorm.roomNumber} 当前入住 ${members.length} 人，超过最大容量 ${dorm.totalBeds} 人！`);
          console.warn(`超员学生: ${members.map(m => `${m.name}(${m.studentId})`).join(', ')}`);
        }
        
        let roomStatus = 1;
        
        if (dorm.status && dorm.status !== 'available') {
          roomStatus = 3;
        } else if (members.length >= dorm.totalBeds) {
          roomStatus = 2;
        } else {
          roomStatus = 1;
        }
        
        // 获取宿舍的性别类型（从宿舍或宿舍楼获取）
        const building = buildings.find(b => b.name === dorm.buildingName);
        const genderType = dorm.genderType || building?.genderType;
        
        return {
          id: dorm.id,
          buildingName: dorm.buildingName,
          roomNumber: dorm.roomNumber,
          genderType: genderType, // 包含性别类型
          maxCapacity: dorm.totalBeds,
          currentCount: members.length,
          roomStatus: roomStatus,
          createdTime: dorm.createdAt || dorm.createdTime || new Date().toISOString(),
          roomType: dorm.roomType,
          floor: dorm.floor,
          orientation: dorm.orientation,
          monthlyRent: dorm.monthlyRent,
          description: dorm.description
        };
      });
      
      // 应用搜索过滤
      let filteredData = [...formattedDormitories];
      
      if (req.query.keyword) {
        const keyword = req.query.keyword.toLowerCase();
        filteredData = filteredData.filter(dorm => 
          dorm.buildingName.toLowerCase().includes(keyword) ||
          dorm.roomNumber.toLowerCase().includes(keyword) ||
          (dorm.description && dorm.description.toLowerCase().includes(keyword))
        );
      }
      
      if (req.query.buildingName) {
        filteredData = filteredData.filter(dorm => dorm.buildingName === req.query.buildingName);
      }
      
      // 支持按buildingId过滤
      if (req.query.buildingId) {
        const buildingId = parseInt(req.query.buildingId);
        filteredData = filteredData.filter(dorm => dorm.buildingId === buildingId);
      }
      
      if (req.query.roomStatus) {
        const status = parseInt(req.query.roomStatus);
        filteredData = filteredData.filter(dorm => dorm.roomStatus === status);
      }
      
      // 分页
      const paginatedData = filteredData.slice(startIndex, endIndex);
      
      const response = {
        data: paginatedData,
        pagination: {
          current: page,
          pageSize: pageSize,
          total: filteredData.length,
          totalPages: Math.ceil(filteredData.length / pageSize)
        },
        success: true
      };
      
      console.log('返回宿舍房间数据:', {
        dataCount: paginatedData.length,
        total: filteredData.length
      });
      
      res.json(response);
    } catch (error) {
      console.error('获取宿舍房间列表失败:', error);
      res.status(500).json({ error: '获取失败' });
    }
  }

  // 创建宿舍楼
  async createDormBuilding(req, res) {
    try {
      const { name, description, totalRooms, genderType } = req.body;
      console.log('创建宿舍楼:', { name, description, genderType });
      
      if (!name) {
        return res.status(400).json({ error: '宿舍楼名称为必填字段' });
      }

      if (!genderType || (genderType !== 'male' && genderType !== 'female')) {
        return res.status(400).json({ error: '宿舍类型为必填字段，必须为 male 或 female' });
      }

      const buildings = dormBuildingModel.findAll();
      
      if (buildings.find(b => b.name === name)) {
        return res.status(400).json({ error: '宿舍楼名称已存在' });
      }

      const newBuilding = {
        name,
        description: description || '',
        genderType: genderType,
        totalRooms: totalRooms || 0
      };

      const createdBuilding = dormBuildingModel.create(newBuilding);
      
      if (createdBuilding) {
        console.log('创建宿舍楼成功:', createdBuilding);
        res.status(201).json(createdBuilding);
      } else {
        res.status(500).json({ error: '保存失败' });
      }
    } catch (error) {
      console.error('创建宿舍楼失败:', error);
      res.status(500).json({ error: '创建失败' });
    }
  }

  // 更新宿舍楼
  async updateDormBuilding(req, res) {
    try {
      const { id } = req.params;
      const { name, description, totalRooms, genderType } = req.body;
      console.log('更新宿舍楼:', id, { name, description, genderType });

      if (genderType && genderType !== 'male' && genderType !== 'female') {
        return res.status(400).json({ error: '宿舍类型必须为 male 或 female' });
      }

      const buildings = dormBuildingModel.findAll();
      
      // 检查宿舍楼名称是否被其他楼使用
      if (buildings.find(b => b.name === name && b.id !== parseInt(id))) {
        return res.status(400).json({ error: '宿舍楼名称已被其他楼使用' });
      }

      const updateData = {
        name,
        description: description || '',
        totalRooms: totalRooms || 0
      };
      
      if (genderType) {
        updateData.genderType = genderType;
      }

      const updatedBuilding = dormBuildingModel.update(id, updateData);

      if (updatedBuilding) {
        console.log('更新宿舍楼成功:', updatedBuilding);
        res.json(updatedBuilding);
      } else {
        res.status(404).json({ error: '宿舍楼不存在' });
      }
    } catch (error) {
      console.error('更新宿舍楼失败:', error);
      res.status(500).json({ error: '更新失败' });
    }
  }

  // 删除宿舍楼
  async deleteDormBuilding(req, res) {
    try {
      const { id } = req.params;
      console.log('删除宿舍楼:', id);
      
      const buildings = dormBuildingModel.findAll();
      const dormitories = dormitoryModel.findAll();
      const students = studentModel.findAll();
      
      // 检查是否有宿舍或学生关联此宿舍楼
      const building = buildings.find(b => b.id === parseInt(id));
      if (building) {
        const relatedDorms = dormitories.filter(dorm => dorm.buildingId === parseInt(id));
        const relatedStudents = students.filter(student => student.dormBuilding === building.name);
        
        if (relatedDorms.length > 0 || relatedStudents.length > 0) {
          return res.status(400).json({ 
            error: `无法删除，该宿舍楼下还有 ${relatedDorms.length} 间宿舍和 ${relatedStudents.length} 名学生` 
          });
        }
      }

      const success = dormBuildingModel.delete(id);
      
      if (success) {
        console.log('删除宿舍楼成功');
        res.json({ message: '删除成功' });
      } else {
        res.status(404).json({ error: '宿舍楼不存在' });
      }
    } catch (error) {
      console.error('删除宿舍楼失败:', error);
      res.status(500).json({ error: '删除失败' });
    }
  }

  // 创建宿舍房间
  async createDormRoom(req, res) {
    try {
      const {
        buildingName,
        roomNumber,
        maxCapacity,
        roomStatus
      } = req.body;
      
      console.log('创建宿舍房间:', { buildingName, roomNumber, maxCapacity, roomStatus });
      
      if (!buildingName || !roomNumber || !maxCapacity) {
        return res.status(400).json({ 
          success: false,
          error: '宿舍楼、房间号和容量为必填字段' 
        });
      }
      
      const capacity = parseInt(maxCapacity);
      if (isNaN(capacity) || capacity < 1 || capacity > 8) {
        return res.status(400).json({ 
          success: false,
          error: '容量必须在1-8之间' 
        });
      }
      
      const dormitories = dormitoryModel.findAll();
      const buildings = dormBuildingModel.findAll();
      
      const building = buildings.find(b => b.name === buildingName);
      if (!building) {
        return res.status(400).json({ 
          success: false,
          error: '宿舍楼不存在' 
        });
      }
      
      const existingRoom = dormitories.find(d => 
        d.buildingName === buildingName && d.roomNumber === roomNumber
      );
      if (existingRoom) {
        return res.status(400).json({ 
          success: false,
          error: '该宿舍楼中此房间号已存在' 
        });
      }
      
      const newDormitory = {
        buildingId: building.id,
        buildingName: buildingName,
        roomNumber: roomNumber,
        genderType: building.genderType || 'male', // 从宿舍楼继承性别类型
        roomType: `${capacity}人间`,
        totalBeds: capacity,
        occupiedBeds: 0,
        availableBeds: capacity,
        floor: 1,
        orientation: '南',
        hasAirConditioner: true,
        hasBalcony: true,
        hasIndependentBathroom: true,
        monthlyRent: 1000,
        status: 'available',
        description: ''
      };
      
      const createdDormitory = dormitoryModel.create(newDormitory);
      
      if (createdDormitory) {
        console.log('创建宿舍房间成功:', createdDormitory);
        
        const responseData = {
          id: createdDormitory.id,
          buildingName: createdDormitory.buildingName,
          roomNumber: createdDormitory.roomNumber,
          maxCapacity: createdDormitory.totalBeds,
          currentCount: 0,
          roomStatus: 1,
          createdTime: createdDormitory.createdAt
        };
        
        res.json({
          success: true,
          data: responseData
        });
      } else {
        res.status(500).json({ 
          success: false,
          error: '保存失败' 
        });
      }
    } catch (error) {
      console.error('创建宿舍房间失败:', error);
      res.status(500).json({ 
        success: false,
        error: '创建失败' 
      });
    }
  }

  // 更新宿舍房间
  async updateDormRoom(req, res) {
    try {
      const { id } = req.params;
      const {
        buildingName,
        roomNumber,
        maxCapacity,
        roomType,
        floor,
        orientation,
        monthlyRent,
        description
      } = req.body;
      
      console.log('更新宿舍房间:', id, { buildingName, roomNumber });

      const capacity = parseInt(maxCapacity);
      if (isNaN(capacity) || capacity < 1 || capacity > 8) {
        return res.status(400).json({ 
          success: false,
          error: '容量必须在1-8之间' 
        });
      }
      
      const dormitories = dormitoryModel.findAll();
      const buildings = dormBuildingModel.findAll();
      const students = studentModel.findAll();
      
      const dormitory = dormitories.find(d => d.id === parseInt(id));
      if (!dormitory) {
        return res.status(404).json({ 
          success: false,
          error: '宿舍不存在' 
        });
      }
      
      // 查找对应的宿舍楼
      const building = buildings.find(b => b.name === buildingName);
      if (!building) {
        return res.status(400).json({ 
          success: false,
          error: '宿舍楼不存在' 
        });
      }
      
      // 检查房间号是否被其他宿舍使用
      const existingRoom = dormitories.find(d => 
        d.buildingName === buildingName && 
        d.roomNumber === roomNumber && 
        d.id !== parseInt(id)
      );
      if (existingRoom) {
        return res.status(400).json({ 
          success: false,
          error: '该宿舍楼中此房间号已被其他宿舍使用' 
        });
      }
      
      // 检查当前入住人数
      const currentMembers = students.filter(student => 
        student.dormBuilding === dormitory.buildingName && 
        student.dormRoom === dormitory.roomNumber
      );
      
      // 检查新容量是否小于当前入住人数
      if (parseInt(maxCapacity) < currentMembers.length) {
        return res.status(400).json({ 
          success: false,
          error: `新容量不能小于当前入住人数（${currentMembers.length}人）` 
        });
      }
      
      // 更新宿舍信息
      const updatedDormitory = dormitoryModel.update(id, {
        buildingId: building.id,
        buildingName: buildingName,
        roomNumber: roomNumber,
        roomType: roomType || `${maxCapacity}人间`,
        totalBeds: parseInt(maxCapacity),
        occupiedBeds: currentMembers.length,
        availableBeds: parseInt(maxCapacity) - currentMembers.length,
        floor: floor || dormitory.floor,
        orientation: orientation || dormitory.orientation,
        monthlyRent: monthlyRent || dormitory.monthlyRent,
        description: description || dormitory.description,
        status: 'available'
      });
      
      if (updatedDormitory) {
        console.log('更新宿舍房间成功:', updatedDormitory);
        
        // 计算新状态
        const newStatus = currentMembers.length >= parseInt(maxCapacity) ? 2 : 1;
        
        res.json({
          success: true,
          data: {
            id: updatedDormitory.id,
            buildingName: updatedDormitory.buildingName,
            roomNumber: updatedDormitory.roomNumber,
            maxCapacity: updatedDormitory.totalBeds,
            currentCount: currentMembers.length,
            roomStatus: newStatus,
            createdTime: updatedDormitory.createdAt
          }
        });
      } else {
        res.status(500).json({ 
          success: false,
          error: '更新失败' 
        });
      }
    } catch (error) {
      console.error('更新宿舍房间失败:', error);
      res.status(500).json({ 
        success: false,
        error: '更新失败' 
      });
    }
  }

  // 删除宿舍房间
  async deleteDormRoom(req, res) {
    try {
      const { id } = req.params;
      console.log('删除宿舍房间:', id);
      
      const dormitories = dormitoryModel.findAll();
      const students = studentModel.findAll();
      
      const dormitory = dormitories.find(d => d.id === parseInt(id));
      if (!dormitory) {
        return res.status(404).json({ 
          success: false,
          error: '宿舍不存在' 
        });
      }
      
      // 检查是否有学生关联此宿舍
      const relatedStudents = students.filter(student => 
        student.dormBuilding === dormitory.buildingName && 
        student.dormRoom === dormitory.roomNumber
      );
      
      if (relatedStudents.length > 0) {
        return res.status(400).json({ 
          success: false,
          error: `无法删除，该宿舍中还有 ${relatedStudents.length} 名学生` 
        });
      }
      
      const success = dormitoryModel.delete(id);
      
      if (success) {
        console.log('删除宿舍房间成功');
        res.json({ 
          success: true,
          message: '删除成功' 
        });
      } else {
        res.status(500).json({ 
          success: false,
          error: '删除失败' 
        });
      }
    } catch (error) {
      console.error('删除宿舍房间失败:', error);
      res.status(500).json({ 
        success: false,
        error: '删除失败' 
      });
    }
  }

  // 更新宿舍成员
  async updateDormMembers(req, res) {
    try {
      const { id } = req.params;
      const { members } = req.body;
      console.log('更新宿舍成员:', id, members);

      const dormitories = dormitoryModel.findAll();
      const students = studentModel.findAll();
      
      const dormitory = dormitories.find(d => d.id === parseInt(id));
      if (!dormitory) {
        return res.status(404).json({ 
          success: false,
          error: '宿舍不存在' 
        });
      }
      
      // 获取当前宿舍的现有成员数量
      const currentMembers = students.filter(student => 
        student.dormBuilding === dormitory.buildingName && 
        student.dormRoom === dormitory.roomNumber
      );
      
      // 验证成员数量不超过最大容量
      if (members && members.length > dormitory.totalBeds) {
        return res.status(400).json({ 
          success: false,
          error: `成员数量不能超过最大容量 ${dormitory.totalBeds}人` 
        });
      }
      
      // 检查宿舍是否已满：如果当前人数已满，且要添加新成员（传入的成员数大于当前成员数），则不允许
      if (members && members.length > currentMembers.length && currentMembers.length >= dormitory.totalBeds) {
        return res.status(400).json({ 
          success: false,
          error: `宿舍已满（当前${currentMembers.length}人，最大容量${dormitory.totalBeds}人），无法添加新成员` 
        });
      }

      // 获取宿舍的性别类型（从宿舍或宿舍楼获取）
      const buildings = dormBuildingModel.findAll();
      const building = buildings.find(b => b.name === dormitory.buildingName);
      const dormGenderType = dormitory.genderType || building?.genderType;
      
      if (!dormGenderType) {
        return res.status(400).json({ 
          success: false,
          error: '宿舍类型未设置，无法分配学生' 
        });
      }

      // 首先清除该宿舍原有的学生关联
      students.forEach(student => {
        if (student.dormBuilding === dormitory.buildingName && 
            student.dormRoom === dormitory.roomNumber) {
          student.dormBuilding = '';
          student.dormRoom = '';
          student.bedNumber = '';
        }
      });

      // 先验证所有成员的性别匹配情况和床位号重复
      const genderErrors = [];
      const bedNumberErrors = [];
      const usedBedNumbers = new Set();
      
      if (members && members.length > 0) {
        for (let i = 0; i < members.length; i++) {
          const member = members[i];
          
          // 验证床位号是否重复
          if (member.bedNumber) {
            const bedNumberStr = String(member.bedNumber);
            if (usedBedNumbers.has(bedNumberStr)) {
              const duplicateMember = members.find((m, idx) => 
                idx < i && m.bedNumber && String(m.bedNumber) === bedNumberStr
              );
              bedNumberErrors.push(`床位号 ${member.bedNumber} 被重复使用${duplicateMember ? `（已分配给${duplicateMember.name || '其他成员'}）` : ''}`);
            } else {
              usedBedNumbers.add(bedNumberStr);
            }
          }
          
          // 查找学生（优先按学号，其次按姓名）
          let studentIndex = students.findIndex(s => s.studentId === member.studentId);
          
          if (studentIndex === -1 && member.name) {
            studentIndex = students.findIndex(s => s.name === member.name);
          }
          
          if (studentIndex !== -1) {
            // 验证学生性别与宿舍类型是否匹配
            const student = students[studentIndex];
            const studentGender = student.gender;
            
            // 将中文性别转换为英文类型
            let studentGenderType = '';
            if (studentGender === '男') {
              studentGenderType = 'male';
            } else if (studentGender === '女') {
              studentGenderType = 'female';
            }
            
            // 验证性别匹配
            if (studentGenderType && studentGenderType !== dormGenderType) {
              genderErrors.push(`学生 ${student.name}（${studentGender}）不能分配到${dormGenderType === 'male' ? '男生' : '女生'}宿舍（${dormitory.buildingName} ${dormitory.roomNumber}）`);
            }
          }
        }
      }
      
      // 如果有床位号重复错误，立即返回
      if (bedNumberErrors.length > 0) {
        return res.status(400).json({ 
          success: false,
          error: bedNumberErrors.join('；')
        });
      }
      
      // 如果有性别验证错误，立即返回
      if (genderErrors.length > 0) {
        return res.status(400).json({ 
          success: false,
          error: genderErrors.join('；')
        });
      }
      
      // 设置新的学生关联和更新详细信息
      if (members && members.length > 0) {
        members.forEach(member => {
          // 查找学生（优先按学号，其次按姓名）
          let studentIndex = students.findIndex(s => s.studentId === member.studentId);
          
          if (studentIndex === -1 && member.name) {
            studentIndex = students.findIndex(s => s.name === member.name);
          }
          
          if (studentIndex !== -1) {
            // 更新现有学生的宿舍信息
            const updatedStudent = {
              ...students[studentIndex],
              dormBuilding: dormitory.buildingName,
              dormRoom: dormitory.roomNumber,
              bedNumber: member.bedNumber || '',
              name: member.name || students[studentIndex].name,
              studentId: member.studentId || students[studentIndex].studentId
            };
            // 使用studentModel的update方法保存学生信息更新
            studentModel.update(students[studentIndex].id, updatedStudent);
          } else if (member.name && member.studentId) {
            // 如果学生不存在，创建新的学生记录（但无法验证性别）
            const newStudent = {
              name: member.name,
              studentId: member.studentId,
              gender: '',
              birthDate: '',
              idCard: '',
              marketingDepartment: '',
              className: '',
              college: '',
              phone: '',
              dormBuilding: dormitory.buildingName,
              dormRoom: dormitory.roomNumber,
              bedNumber: member.bedNumber || '',
              status: 'active',
              enrollmentDate: new Date().toISOString().split('T')[0]
            };
            studentModel.create(newStudent);
          }
        });
      }

      // 确保清除了其他学生的关联信息并保存
      students.forEach(student => {
        if (student.dormBuilding === dormitory.buildingName && 
            student.dormRoom === dormitory.roomNumber) {
          // 检查该学生是否在新的成员列表中
          const isInNewMembers = members && members.some(m => m.studentId === student.studentId);
          if (!isInNewMembers) {
            // 清除不在新成员列表中的学生关联
            studentModel.update(student.id, {
              ...student,
              dormBuilding: '',
              dormRoom: '',
              bedNumber: ''
            });
          }
        }
      });

      // 更新宿舍的入住人数和成员信息
      const updatedDormitory = dormitoryModel.update(id, {
        occupiedBeds: members ? members.length : 0,
        availableBeds: dormitory.totalBeds - (members ? members.length : 0),
        members: members || []
      });

      if (updatedDormitory) {
        console.log('更新宿舍成员成功');
        res.json({ 
          success: true,
          message: '成员更新成功',
          data: {
            members: members || [],
            occupiedBeds: members ? members.length : 0
          }
        });
      } else {
        res.status(500).json({ 
          success: false,
          error: '更新失败' 
        });
      }
    } catch (error) {
      console.error('更新宿舍成员失败:', error);
      res.status(500).json({ 
        success: false,
        error: '更新失败' 
      });
    }
  }
}